package com.example.demo99.Service.Impl;

import com.example.demo99.Entity.PointLog;
import com.example.demo99.Entity.User;
import com.example.demo99.Mapper.PointLogMapper;
import com.example.demo99.Mapper.UserMapper;
import com.example.demo99.Service.PointService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class PointServiceImpl implements PointService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PointLogMapper pointLogMapper;

    /**
     * 用户下单后赠送积分
     */

    @Transactional
    public void addPointsAfterOrder(Integer userId, Integer orderId, BigDecimal orderTotal) {
        int pointsToAdd = orderTotal.intValue(); // 例如：1元 = 1积分，可调整比例

        // 插入积分变动日志
        PointLog log = new PointLog();
        log.setUserId(userId);
        log.setChange(pointsToAdd);
        log.setDescription("下单获得积分");
        log.setOrderId(orderId);
        log.setCreatedAt(LocalDateTime.now());
        pointLogMapper.insertPointLog(log);

        // 获取用户原始积分
        User user = userMapper.getUserById(userId);
        int newPoints = user.getPoints() + pointsToAdd;
        int newTotal = user.getTotalPoints() + pointsToAdd;

        // 更新用户积分
        userMapper.updatePoints(userId, newPoints, newTotal);

        // 判断是否升级（可选）
        String newLevel = judgeLevel(newTotal);
        if (!newLevel.equals(user.getLevel())) {
            userMapper.updateLevel(userId, newLevel);
        }
    }

    // 简单的会员等级规则（可调整）
    private String judgeLevel(int totalPoints) {
        if (totalPoints >= 1000) return "金卡会员";
        if (totalPoints >= 500) return "银卡会员";
        return "普通会员";
    }
}
